<template>
  <div class="page-city">
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft">
    </van-nav-bar>
    <!-- 当前城市 -->
    <div class="nowCity">当前城市：{{ nowCity }}</div>
    <!-- 分组列表数据 -->
    <div class="list">
      <div
        class="item"
        :class="group.groupName"
        v-for="group in citiGroup"
        :key="group.groupName"
      >
        <div class="item-group">
          {{ group.groupName }}
        </div>
        <ul>
          <li v-for="city in group.groupList" :key="city.cityId">
            {{ city.name }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 快速选择 -->
    <div class="ks-list">
      <div
        class="ks-list_item"
        :class="{ active: activeName === item }"
        v-for="item in qsList"
        :key="item"
        @click="handleClick(item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<!-- 
    城市列表期望的数据如下：
    [
        {
            groupName:"A",
            groupList:[
                {
                    ...,
                    name:"鞍山"
                },
                {
                    ...,
                    name:"安庆"
                }
            ]
        },
        {
            groupName:"B",
            groupList:[
                {
                    ...,
                    name:"北京"
                },
                {
                    ...,
                    name:"保定"
                }
            ]
        },
    ]
 -->

<script lang="ts" setup>
import router from "@/router";
import axios from "axios";
import { ref, onMounted, computed, onUnmounted, nextTick } from "vue";

interface ICity {
  cityId: number;
  isHot: 0 | 1;
  name: string;
  pinyin: string;
}
interface IGroup {
  groupName: string;
  groupList: ICity[];
}
interface IOffset {
  name: string;
  top: number;
}

const cities = ref<ICity[]>([]);
//分组元素距离顶部距离的一个集合
const cityGroupOffsetTop: IOffset[] = [];

//判断是否高亮的数据 当前高亮显示的分组名
const activeName = ref("A"); //默认A
//城市列表分组
const citiGroup = computed(() => {
  let result: IGroup[] = [];

  cities.value.forEach((city) => {
    //1.取出当前城市的拼音首字母
    const name = city.pinyin.substring(0, 1).toUpperCase();
    //2.判断当前name是否存在 result 结果中已经存在了
    const index = result.findIndex((group) => group.groupName === name);
    if (index === -1) {
      //不存在,将当前city 组装成相应格式,追加到result中
      result.push({
        groupName: name,
        groupList: [city],
      });
    } else {
      //存在，将当前city追加到result中对应分组中的groupList 里面去
      result[index].groupList.push(city);
    }
  });
  //做一个数组排序后再返回 按字母排序A~Z
  return result.sort((a, b) => {
    return a.groupName.charCodeAt(0) - b.groupName.charCodeAt(0);
  });
  return result;
});
//快速选择
const qsList = computed(() => {
  return citiGroup.value.map((group) => group.groupName);
});

//  右侧快速选择 点击事件处理函数
const handleClick = (item: string) => {
  //1.获取被点击的元素距离顶部的距离
  let offsetTop = (document.querySelector(`.${item}`) as HTMLDivElement)
    .offsetTop;
  //2.直接操作scrollTop(滚动条)距离顶部的距离
  //    document.documentElement.scrollTop = offsetTop;
  document.documentElement.scrollTo({
    top: offsetTop,
    behavior: "smooth", //使滚动条有滚动的动画效果
  });
};

const nowCity = ref();
//请求当前城市定位 这里用腾讯地图开放平台的接口
const getLocation = async () => {
  //直接请求有跨域！
  const response = await axios.get(
    "/ws/location/v1/ip?key=RARBZ-ENDW5-DBWIW-QSGIZ-YGYL6-PCFGT"
  );
  // console.log(response.data.result.ad_info)
  // return response.data.result.ad_info;
  nowCity.value = response.data.result.ad_info.city;
};

//请求城市数据 这里用卖座电影的接口
const fetchData = async () => {
  const response = await axios.get("https://m.maizuo.com/gateway?k=180393", {
    headers: {
      "X-Host": "mall.film-ticket.city.list",
    },
  });
  // console.log(response.data.data.cities)
  cities.value = response.data.data.cities;
  nextTick(() => {
    //    console.log((document.querySelector(".B")as HTMLDivElement).offsetTop)
    //将分组的元素距离顶部的距离给记录下来
    qsList.value.forEach((item) => {
      const top = (document.querySelector(`.${item}`) as HTMLDivElement)
        .offsetTop;

      cityGroupOffsetTop.push({
        name: item,
        top,
      });
    });
  });
};

const handleScroll = () => {
  //1.当前滚动条距离顶部的距离
  const scrllTop = document.documentElement.scrollTop;
  // console.log(scrllTop)
  //2.循环判断当前scrllTop的值在哪个元素的范围内
  for (let i = cityGroupOffsetTop.length - 1; i >= 0; i--) {
    const item = cityGroupOffsetTop[i];
    if (scrllTop >= item.top) {
      // console.log(item.name);
      activeName.value = item.name;
      //只要有符合的就不往下遍历了,直接break退出循环
      break;
    }
  }
};

onMounted(() => {
  //调用相关处理函数函数
  //请求城市数据
  fetchData();
  //请求当前城市定位
  getLocation();

  //监听滚动条事件
  window.addEventListener("scroll", handleScroll);
});

// 收尾工作
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});

//返回上一页
const onClickLeft = () => {
  router.back();
};
</script>

<style lang="scss" scoped>
//当前城市
.nowCity {
  padding: 10px 5px;
}

//城市列表
.item {
  overflow: hidden;

  .item-group {
    padding-left: 5px;
    height: 36px;
    line-height: 36px;
    color: #fff;
    background: green;
  }

  li {
    padding-left: 16px;
    height: 36px;
    line-height: 36px;
  }
}

// 快速选择样式
.ks-list {
  position: fixed;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 30px;
  // background-color: aqua;

  &_item {
    height: 20px;
    line-height: 20px;
    padding-top: 3px;
    font-size: 16px;
    text-align: center;

    &.active {
      background-color: #ccc;
    }
  }
}
</style>
